﻿
#include <thread>
#include "Network/TCPServer.h"
#include "Network/TCPClient.h"
#include "Async/PackagedTask.h"


#include "Platform/Socket/SocketPlatform.h"


TThreadSafeSharedPtr<CTCPClient> CTCPServer::GetNextPendingClient()
{
    std::lock_guard<std::mutex> Lock(PendingAcceptSocketsMutex);
    if(PendingAcceptSockets.empty())
    {
        return nullptr;
    }

    auto Client = CTCPClient::Create();
    Client->InitWith(PendingAcceptSockets.front());
    PendingAcceptSockets.pop();
    return Client;
}

void CTCPServer::WaitForClientConnected()
{
    while(true)
    {
        if(!PendingAcceptSockets.empty())
        {
            return;
        }
        std::this_thread::yield();
    }
}

bool CTCPServer::IsListening()
{
    std::lock_guard<std::mutex> Lock(ListenSocketMutex);
    return State==ETCPServerState::Listening;
}

TThreadSafeSharedPtr<CTCPServer> CTCPServer::Create()
{
    TThreadSafeSharedPtr<CTCPServer> Server(new CTCPServer());
    return Server;
}

CTCPServer::CTCPServer()
{
    PlatformData=new CSocketPlatformData();
}


CTCPServer::~CTCPServer()
{
    StopListen();

    delete PlatformData;
}

